<?php
declare (strict_types = 1);

namespace app\store\controller;

use app\store\model\Employee as EmployeeModel;
use app\store\model\User as UserModel;
use app\store\service\Employee as EmployeeService;

class Employee extends Controller
{
    public function list()
    {
        $model = new EmployeeModel;
        $list = $model->getList();
        return $this->renderSuccess(compact('list'));
    }

    public function detail(int $employeeId)
    {
        $employee = EmployeeModel::get($employeeId);
        return $this->renderSuccess(compact('employee'));
    }

    public function add()
    {
        // 新增记录
        $model = new EmployeeModel;
        if ($model->add($this->postForm())) {
            return $this->renderSuccess('添加成功');
        }
        return $this->renderError($model->getError() ?: '添加失败');
    }

    public function edit(int $employeeId)
    {
        $model = EmployeeModel::get($employeeId);
        // 更新记录
        if ($model->edit($this->postForm())) {
            return $this->renderSuccess('更新成功');
        }
        return $this->renderError($model->getError() ?: '更新失败');
    }

    public function delete(int $employeeId)
    {
        $model = EmployeeModel::get($employeeId);
        if (!$model->remove($employeeId)) {
            return $this->renderError($model->getError() ?: '删除失败');
        }
        return $this->renderSuccess('删除成功');
    }

    public function code(int $employeeId)
    {
      $buffer = EmployeeService::getCode($employeeId, 'pages/bind/bind');
      return response($buffer)->header([
        'Access-Control-Allow-Origin' => '*'
      ]);
    }

    // 获取指定员工的绑定信息
    public function binding(int $employeeId)
    {
        $employee = EmployeeModel::get($employeeId, ['user.avatar']);
        if(!$employee) {
            return $this->renderError('该员工不存在');
        }
        return $this->renderSuccess(compact('employee'));
    }
}
